function pad (source, length) {
  let pre = ''
  const negative = source < 0
  const string = String(Math.abs(source))
  if (string.length < length) {
    pre = new Array(length - string.length + 1).join('0')
  }
  return (negative ? '-' : '') + pre + string
}
const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

module.exports = {
  format (date, pat) {
    let source = date
    let pattern = pat
    if (typeof date === 'string') {
      pattern = date
      source = new Date()
    }
    pattern = pattern || 'yyyy-MM-dd HH:mm:ss'
    // yyyy-MM-dd HH:mm:ss.S 带毫秒
    function replacer (patternPart, result) {
      pattern = pattern.replace(patternPart, result)
    }
    const year = source.getFullYear()
    const month = source.getMonth() + 1
    const date2 = source.getDate()
    const hours = source.getHours()
    const minutes = source.getMinutes()
    const seconds = source.getSeconds()
    const milliseconds = source.getMilliseconds()
    replacer(/yyyy/g, pad(year, 4))
    replacer(/yy/g, pad(parseInt(year.toString().slice(2), 10), 2))
    replacer(/MM/g, pad(month, 2))
    replacer(/M/g, month)
    replacer(/dd/g, pad(date2, 2))
    replacer(/d/g, date2)
    replacer(/HH/g, pad(hours, 2))
    replacer(/H/g, hours)
    replacer(/hh/g, pad(hours % 12, 2))
    replacer(/h/g, hours % 12)
    replacer(/mm/g, pad(minutes, 2))
    replacer(/m/g, minutes)
    replacer(/ss/g, pad(seconds, 2))
    replacer(/s/g, seconds)
    replacer(/S/g, milliseconds)
    return pattern
  },
  addMonths (date, num) {
    const tmpdtm = date.getDate()
    date.setMonth(date.getMonth() + num)
    if (tmpdtm > date.getDate()) this.addDays(date, -date.getDate())
    return date
  },
  addDays (date, num) {
    date.setTime(date.getTime() + (num * 86400000))
    return date
  },
  addHours (date, num) {
    date.setHours(date.getHours() + num)
    return date
  },
  addMinutes (date, num) {
    date.setMinutes(date.getMinutes() + num)
    return date
  },
  addSeconds (date, num) {
    date.setSeconds(date.getSeconds() + num)
    return date
  },
  getDayName: function (date) {
    return dayNames[date.getDay()]
  },
  /**
   * 计算时间差
   * @name LT.Date.dateDiff
   * @function
   * @grammar LT.Date.dateDiff(start, end, diff)
   * @param {Date} start 开始时间
   * @param {Date} end 结束时间
   * @param {String} diff 计算单位，Y：年，M：月，D：日，H：时，m：分，S：秒
   *
   * @return {Int} 时间差
   */
  dateDiff: function (start, end, diff) {
    var diffn = 1
    switch (diff) {
      case 'S':
        diffn = 1000
        break
      case 'm':
        diffn = 1000 * 60
        break
      case 'H':
        diffn = 1000 * 3600
        break
      case 'D':
        diffn = 1000 * 3600 * 24
        break
      case 'M':
        diffn = 1000 * 3600 * 24 * 31
        break
      case 'Y':
        diffn = 1000 * 3600 * 24 * 365
        break
      default:
        break
    }
    return parseInt((start.getTime() - end.getTime()) / parseInt(diffn))
  }
}
